package com.eatme.web.app.coupon.distribution.vo;

import com.eatme.web.app.coupon.common.constant.PeriodType;
import com.eatme.web.app.coupon.distribution.constant.CouponStatus;
import com.eatme.web.app.coupon.distribution.entity.Coupon;
import org.apache.commons.lang3.time.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户优惠券的分类, 根据优惠券状态
 */
public class CouponClassify {

    /** 可以使用的  */
    private List<Coupon> usable;

    /** 已使用的  */
    private List<Coupon> used;

    /** 已过期的  */
    private List<Coupon> expired;

    public CouponClassify() {
    }

    public CouponClassify(List<Coupon> usable, List<Coupon> used, List<Coupon> expired) {
        this.usable = usable;
        this.used = used;
        this.expired = expired;
    }

    public List<Coupon> getUsable() {
        return usable;
    }

    public void setUsable(List<Coupon> usable) {
        this.usable = usable;
    }

    public List<Coupon> getUsed() {
        return used;
    }

    public void setUsed(List<Coupon> used) {
        this.used = used;
    }

    public List<Coupon> getExpired() {
        return expired;
    }

    public void setExpired(List<Coupon> expired) {
        this.expired = expired;
    }

    /**
     * 对当前的优惠券进行分类
     * @param coupons
     * @return
     */
    public static CouponClassify classify(List<Coupon> coupons) {

        List<Coupon> usable = new ArrayList<>(coupons.size());
        List<Coupon> used = new ArrayList<>(coupons.size());
        List<Coupon> expired = new ArrayList<>(coupons.size());

        coupons.forEach(coupon -> {

            boolean isTimeExpire;
            long curTime = new Date().getTime();

            // 判断优惠券是否过期
            if (coupon.getTemplateSDK().getRule().getExpiration().getPeriod().equals(PeriodType.REGULAR.getCode())) {
                isTimeExpire = coupon.getTemplateSDK().getRule().getExpiration().getDeadLine() <= curTime;
            }else {
                isTimeExpire = DateUtils.addDays(
                        coupon.getAssignTime(),
                        coupon.getTemplateSDK().getRule().getExpiration().getGap()).getTime() <= curTime;
            }

            if (coupon.getStatus()== CouponStatus.USED) {
                used.add(coupon);
            }else if (coupon.getStatus()== CouponStatus.EXPIRED||isTimeExpire) {
                expired.add(coupon);
            }else {
                used.add(coupon);
            }

        });
        return new CouponClassify(usable,used,expired);
    }
}
